package com.taotao.cart.interceptors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.taotao.cart.pojo.User;
import com.taotao.cart.service.UserService;
import com.taotao.cart.threadlocal.UserThreadLocal;
import com.taotao.common.utils.CookieUtils;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {
	
	@Autowired
	private UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取请求中的token信息
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		// 判断token信息
		if(StringUtils.isEmpty(token)){
			// 如果没有token，跳转到登陆页面
			return true;
		}
		// 根据token到单点登录系统，验证登陆状态
		User user = this.userService.queryUserByToken(token);
		// 验证不通过，跳转到登陆页
		if(user == null){
			return true;
		}
		UserThreadLocal.set(user);
		// 验证通过，放行
		return true;
	}

	/* 
	 * 释放资源
	 * (non-Javadoc)
	 * @see org.springframework.web.servlet.handler.HandlerInterceptorAdapter#afterCompletion(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.Object, java.lang.Exception)
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		UserThreadLocal.remove();
	}
}
